<template>
  <div class="box-yuyi">
    <div class="box-left" v-loading="treeLoading">
      <el-tree
        ref="categoryTree"
        :data="treeData"
        node-key="id"
        :props="propsTree"
        default-expand-all
        :expand-on-click-node="false"
        @node-click="handleNodeClick">
          <span class="el-tree-node__label" slot-scope="{ node }">
            <span>
              <i class="el-icon-folder close"></i>
              <i class="el-icon-folder-opened open"></i>
              {{ node.label }}
            </span>
          </span>
      </el-tree>
    </div>
    <div class="box-content">
      <!--案卷-->
      <book-file-archives :idTable="idTable"
                          :idCategory="idCategory"
                          @handleToIn="handleToIn"
                          v-if="type === 'file'"></book-file-archives>
      <!--卷内-->
      <book-in-archives :idTable="idTable"
                        :idCategory="idCategory"
                        :ajId="ajId"
                        @handleToFile="handleToFile"
                        @handleGetFile="handleGetFile"
                        v-if="type === 'in'"></book-in-archives>
      <!--件-->
      <simplify-book-archives :idTable="idTable"
                              :idCategory="idCategory"
                              v-if="type === 'simplify'"></simplify-book-archives>
    </div>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { getSelfCategoryTree } from '../../../api/category/category'
import SimplifyBookArchives from './ElectronicsArchives/Electron/SimplifyBookArchives'
import BookInArchives from './ElectronicsArchives/Electron/BookInArchives'
import BookFileArchives from './ElectronicsArchives/Electron/BookFileArchives'
import { getTableLabelNode } from '../../../api/user/userSet'
import { mapFields } from 'vuex-map-fields'

export default {
  // 电子档案
  name: 'ElectronicsArchives',
  components: {
    SimplifyBookArchives,
    BookInArchives,
    BookFileArchives
  },
  data () {
    return {
      propsTree: {
        label: 'name',
        value: 'id',
        children: 'children'
      },
      treeLoading: true,
      treeData: [],
      idTable: '',
      idCategory: '',
      type: '',
      ajId: '',
      rowTreeData: {},
      params: []
    }
  },
  mounted () {
    this.getCategoryFormJson()
    if (this.$route.query.gdbs) {
      this.params = [{
        name: 'gdbs',
        op: 'in',
        values: JSON.parse(this.$route.query.gdbs)
      }]
    }
    // 默认收起左侧导航栏
    this.setNavNarrow(true)
    this.getTreeDoorClass()
  },
  computed: {
    ...mapFields('electronicsFile/getHead', { sortRetrieved: 'sortRetrieved' }),
    nextData () {
      let treeRowData = {}
      const findRow = (data) => {
        data.map((item) => {
          if (this.idCategory === item.idCategory) {
            if (this.type === 'file' && item.nodeType === 'jn') {
              // 卷内跳案卷获取案卷信息
              treeRowData = item
            } else if (this.type === 'in' && item.nodeType === 'aj') {
              // 案卷跳卷内获取卷内信息
              treeRowData = item
            }
          }
          if (item.children) {
            findRow(item.children)
          }
        })
      }
      if (this.treeData) {
        findRow(this.treeData)
      }
      return treeRowData
    }
  },
  methods: {
    ...mapActions('profile/getDh', ['getDh']),
    ...mapActions('profile/getCategoryType', ['getCategoryFormJson']),
    ...mapActions('profile/navNarrow', ['setNavNarrow']),
    ...mapActions('electronicsFile/getHead', ['getTableHead', 'getTableList']),
    // ...mapActions('electronicsFile/getList', ['getTableList']),
    ...mapActions('electronicsFile/getAnjuan', ['getTableajHead', 'getTableajList']),
    ...mapActions('electronicsFile/setSearchCondition', ['setSearchCondition']),
    getTreeDoorClass () {
      // 左侧获取门类
      /* getCategoryTree('wjModel', this.$route.query.isNotAjJnNode).then(res => {
          this.treeData = res.data.data
          this.treeLoading = false
        }).catch(() => {
          this.treeLoading = false
        }) */
      getSelfCategoryTree('wjModel', this.$route.query.isNotAjJnNode).then(res => {
        this.treeData = res.data.data
        this.treeLoading = false
      }).catch(() => {
        this.treeLoading = false
      })
    },
    async getTableLabel (data, node) {
      // 获取表序列节点
      const param = {
        nodeType: data.nodeType.indexOf('seq') >= 0 ? 'seq' : 'table',
        pageNo: 1,
        pageSize: 100,
        params: []
      }
      if (this.$route.query.gdbs) {
        param.params = [{
          name: 'gdbs',
          op: 'in',
          values: JSON.parse(this.$route.query.gdbs)
        }]
      }

      if (data.nodeType.indexOf('seq') >= 0) {
        param.sequenceId = data.sequenceId
        data.conditions.map(item => {
          param.params.push({
            name: item.mdCode,
            op: item.value === null ? 'isNull' : 'eq',
            value: item.value
          })
        })
      }
      if (param.params.length < 1) {
        delete param.params
      }

      await getTableLabelNode(data.table[0].idTable, param).then(res => {
        res.data.data.map((items) => {
          const dataNode = {}
          Object.keys(items).forEach(key => {
            if (key === 'tableId') {
              dataNode.table = [{ idTable: items[key] }]
            } else {
              dataNode[key] = items[key]
            }
          })
          dataNode.name = items.title
          dataNode.id = items.value
          dataNode.pid = items.id
          dataNode.idCategory = this.idCategory
          dataNode.conditions = []
          if (data.conditions) {
            data.conditions.map(item => {
              dataNode.conditions.push(item)
            })
          }
          dataNode.conditions.push({
            mdCode: items.mdCode,
            value: items.value
          })

          this.$refs.categoryTree.append(dataNode, node)
        })
      })
    },
    handleNodeClick (data, node) {
      this.rowTreeData = data
      this.ajId = ''
      if (this.$route.query.gdbs) {
        this.params = [{
          name: 'gdbs',
          op: 'in',
          values: JSON.parse(this.$route.query.gdbs)
        }]
      } else {
        this.params = []
      }
      this.handleToPage(data, node)
    },
    handleToPage (data, node) {
      this.idCategory = data.idCategory // || this.idCategory
      if (this.idCategory) {
        if (data.nodeType.indexOf('seq') < 0) {
          if (!data.children) {
            if (this.idTable !== data.table[0].idTable) {
              this.getTableLabel(data, node)
            }
          }
          if (data.table) {
            // 获取表头
            this.getDataList(data)
          }
        } else if (data.nodeType.indexOf('seq') >= 0) {
          if (data.conditions) {
            data.conditions.map(item => {
              this.params.push({
                name: item.mdCode,
                op: item.value === null ? 'isNull' : 'eq',
                value: item.value
              })
            })
          }
          this.getDataList(data)
          if (data.hasNext && !data.children) {
            this.getTableLabel(data, node)
          }
        }

        if (data.nodeType.indexOf('jh') >= 0) {
          // 件
          this.type = 'simplify'
          return
        }
        if (data.nodeType.indexOf('aj') >= 0) {
          // 案卷
          this.type = 'file'
          return
        }
        if (data.nodeType.indexOf('jn') >= 0) {
          // 卷内
          this.type = 'in'
        }
      }
      // this.type = ''
    },
    async getDataList (data) {
      // 获取表头
      this.idTable = data.table[0].idTable
      const queryData = {
        pageNo: 1,
        pageSize: 20
      }
      if (this.params.length > 0) {
        queryData.params = this.params
      } else {
        delete queryData.params
      }
      // 设置左侧选择后的搜索条件
      await this.setSearchCondition(this.params)

      await this.getTableHead(data.table[0].idTable)

      queryData.sorters = []
      this.sortRetrieved.map(item => {
        queryData.sorters.push({
          asc: item.ascending === 1,
          name: item.mdCode
        })
      })
      if (queryData.sorters.length < 1) {
        delete queryData.sorters
      }
      this.getTableList({
        idTable: data.table[0].idTable,
        data: queryData
      })
      this.getDh(this.idCategory)
    },
    handleToFile (row) {
      // 跳转案卷
      this.params = [{
        name: 'id',
        op: 'eq',
        value: row.id_aj
      }]
      this.handleToPage(this.nextData)
    },
    handleToIn (row) {
      // 跳转卷内
      this.ajId = row.id
      this.params = [{
        name: 'id_aj',
        op: 'eq',
        value: row.id
      }]
      this.handleToPage(this.nextData)
    },
    handleGetFile () {
      // 挂接案卷获取案卷信息
      const data = this.nextData
      if (data.table && this.idTable !== data.table[0].idTable) {
        // 获取表头
        this.idTable = data.table[0].idTable
        const queryData = {
          pageNo: 1,
          pageSize: 20
        }
        this.getTableajHead(data.table[0].idTable)
        this.getTableajList({
          idTable: data.table[0].idTable,
          data: queryData
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .box-yuyi {
    margin: 0 -10px;

    .box-left {
      padding-top: 10px;
    }
  }

  ::v-deep .el-drawer__header {
    color: #333;
    font-weight: bolder;
    padding: 15px 20px;
    margin-bottom: 0;
  }
</style>
